package com.hxkcloud.patient.activitys;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;
import com.hxkcloud.patient.R;
import com.hxkcloud.patient.YjhApplication;
import com.hxkcloud.patient.beans.LoginInfo;
import com.hxkcloud.patient.beans.RegisterPatientInfo;
import com.hxkcloud.patient.beans.resultbeans.ObjectResultBean;
import com.hxkcloud.patient.dborm.LoginInfoDao;
import com.hxkcloud.patient.popup.AreaSelectPop;
import com.hxkcloud.patient.request.MessageCode;
import com.hxkcloud.patient.request.YiJiaHuNetWorkUtils;
import com.hxkcloud.patient.utils.SharedPreferenceUtil;
import com.hxkcloud.patient.utils.StringUtil;
import com.hxkcloud.patient.views.MyToast;
import com.zhuge.analysis.stat.ZhugeSDK;

import org.json.JSONException;
import org.json.JSONObject;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by ray_lei on 2016/7/21.
 */
public class UserInfoActivity extends BaseActivity implements View.OnClickListener, AreaSelectPop.onAreaSelectListener {

    private LinearLayout ll_title;
    private ImageView iv_back;
    private TextView tv_title;
    private EditText et_height;
    private EditText et_weight;
    //    private EditText et_address;
    private TextView tv_address;
    private EditText et_number;//病案号
    private Button bt_finish;

    private MyToast myToast;

    private boolean heightInput = false;
    private boolean weightInput = false;
    private boolean addressInput = false;
    private boolean numberInput = false;

    private String tel = "";
    private String password = "";

    private String name = "";
    private String age = "";
    private String sex = "";

    private String province = "";
    private String city = "";
    private String area = "";
    private String areaId = "";

    private String height;
    private String weight;

    private ObjectResultBean<RegisterPatientInfo> resultBean;

    private AreaSelectPop areaSelectPop;

    @Override
    protected void updateByHandler(Message msg) {
        switch (msg.what) {
            case MessageCode.NETWORKCODE_REGISTERPATIENT_SUCCESS:
                if (msg.obj != null) {
                    resultBean = (ObjectResultBean<RegisterPatientInfo>) msg.obj;
                    loginInfo = new LoginInfo();
                    loginInfo.setDepartmentId("");
                    loginInfo.setDepartment("");
                    loginInfo.setAddress(province + city + area);
                    loginInfo.setAddressId(areaId);
                    loginInfo.setAge(age);
                    loginInfo.setHeadImg("");
                    loginInfo.setHeight(height);
                    loginInfo.setWeight(weight);
                    loginInfo.setSex(sex);
                    loginInfo.setName(name);
                    loginInfo.setUserId(resultBean.getData().getUserId());
                    loginInfo.setUserStyle(YjhApplication.userstyle_patient);
                    loginInfo.setPatientId(resultBean.getData().getPatientId());
                    loginInfo.setCaseNumber(et_number.getText().toString().trim());
                    LoginInfoDao loginInfoDao = new LoginInfoDao(mContext);
                    loginInfoDao.setUser(loginInfo);

                    new Thread() {
                        @Override
                        public void run() {
                            super.run();
                            try {
                                EMClient.getInstance().createAccount("ejh" + tel, "123456");
                                emClientLogin();
                            } catch (HyphenateException e) {
                                e.printStackTrace();
                                Log.e("EASE", e.toString());
                            }
                        }
                    }.start();

                    JPushInterface.setAlias(mContext, tel, null);

                    //zhugeio
                    try {
                        JSONObject personObject = new JSONObject();
                        personObject.put("name", name);
                        personObject.put("phone", tel);
                        ZhugeSDK.getInstance().identify(getApplicationContext(), resultBean.getData().getUserId(),
                                personObject);
                    } catch (JSONException e) {
                    }

                    SharedPreferenceUtil.setIsrunning(mContext, true);
                    SharedPreferenceUtil.setLoginAccount(mContext, tel);
                    SharedPreferenceUtil.setLoginPassword(mContext, password);

                    myToast.setLongMsg(resultBean.getMessage());
                    Intent intent = new Intent(mContext, UserFragmentActivity.class);
                    intent.putExtra("page", 0);//跳到发现页
                    startActivity(intent);
                    removeAll();
                    return;
                }

                break;
            case MessageCode.NETWORKCODE_REGISTERPATIENT_FAILURE:
                if (msg.obj != null) {
                    myToast.setLongMsg((String) msg.obj);
                    return;
                }

                break;
        }
    }

    //环信登录
    private void emClientLogin() {
        EMClient.getInstance().login("ejh" + tel, "123456", new EMCallBack() {
            @Override
            public void onSuccess() {
                //以下两个方法是为了保证进入主页面后本地会话和群组都 load 完毕
                EMClient.getInstance().chatManager().loadAllConversations();
                EMClient.getInstance().groupManager().loadAllGroups();
                Log.e("EASE", "loginSuccess");
                dismisssLoading();
            }

            @Override
            public void onError(int i, String s) {
                Log.e("EASE", "登录聊天服务器失败！" + s);
            }

            @Override
            public void onProgress(int i, String s) {

            }
        });

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_layout_userinfo);
        if (getIntent().hasExtra("tel")) {
            tel = getIntent().getStringExtra("tel");
        }
        if (getIntent().hasExtra("password")) {
            password = getIntent().getStringExtra("password");
        }
        if (getIntent().hasExtra("name")) {
            name = getIntent().getStringExtra("name");
        }
        if (getIntent().hasExtra("age")) {
            age = getIntent().getStringExtra("age");
        }
        if (getIntent().hasExtra("sex")) {
            sex = getIntent().getStringExtra("sex");
        }
        initView();
        areaSelectPop = new AreaSelectPop(UserInfoActivity.this, this);
    }

    @Override
    protected void initView() {
        ll_title = (LinearLayout) findViewById(R.id.ll_title);
        iv_back = (ImageView) findViewById(R.id.iv_title_back);
        tv_title = (TextView) findViewById(R.id.tv_title_title);
        et_height = (EditText) findViewById(R.id.et_userinfo_height);
        et_weight = (EditText) findViewById(R.id.et_userinfo_weight);
//        et_address = (EditText) findViewById(R.id.et_userinfo_address);
        tv_address = (TextView) findViewById(R.id.tv_userinfo_address);
        et_number = (EditText) findViewById(R.id.et_userinfo_number);
        bt_finish = (Button) findViewById(R.id.bt_userinfo_finish);

        setTitlePadding(ll_title);
        iv_back.setOnClickListener(this);
        iv_back.setVisibility(View.VISIBLE);
        tv_title.setText(getResources().getString(R.string.personalinfo));

//        et_address.setFocusable(false);
//        et_address.setOnClickListener(this);
        tv_address.setOnClickListener(this);
        bt_finish.setOnClickListener(this);

        bt_finish.setBackgroundResource(R.drawable.bt_grey);
        bt_finish.setEnabled(false);

        et_height.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (StringUtil.isEmpty(s.toString())) {
                    heightInput = false;
//                    bt_finish.setBackgroundResource(R.drawable.bt_grey);
//                    bt_finish.setEnabled(false);
                } else {
                    if (Double.parseDouble(s.toString()) > 0 && Double.parseDouble(s.toString()) < 300) {

                    } else {
                        toastMsg(getResources().getString(R.string.userinfo_text_inputrightheight));
                        return;
                    }
                    heightInput = true;
//                    if (weightInput && addressInput) {
//                        bt_finish.setBackgroundResource(R.drawable.bg_btn_lightgreen_corner);
//                        bt_finish.setEnabled(true);
//                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        et_weight.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (StringUtil.isEmpty(s.toString())) {
                    weightInput = false;
//                    bt_finish.setBackgroundResource(R.drawable.bt_grey);
//                    bt_finish.setEnabled(false);
                } else {
                    if (Double.parseDouble(s.toString()) > 0 && Double.parseDouble(s.toString()) < 300) {

                    } else {
                        toastMsg(getResources().getString(R.string.userinfo_text_inputrightweight));
                        return;
                    }
                    weightInput = true;
//                    if (heightInput && addressInput) {
//                        bt_finish.setBackgroundResource(R.drawable.bg_btn_lightgreen_corner);
//                        bt_finish.setEnabled(true);
//                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        et_number.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (StringUtil.isEmpty(s.toString())) {
                    numberInput = false;
                    bt_finish.setBackgroundResource(R.drawable.bt_grey);
                    bt_finish.setEnabled(false);
                } else {
                    numberInput = true;
                    if (addressInput) {
                        bt_finish.setBackgroundResource(R.drawable.bg_btn_lightgreen_corner);
                        bt_finish.setEnabled(true);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

//        et_address.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//
//            }
//
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                if (StringUtil.isEmpty(s.toString())) {
//                    addressInput = false;
//                    bt_finish.setBackgroundResource(R.drawable.bt_grey);
//                    bt_finish.setEnabled(false);
//                } else {
//                    addressInput = true;
//                    if (weightInput && heightInput) {
//                        bt_finish.setBackgroundResource(R.drawable.bt_blue);
//                        bt_finish.setEnabled(true);
//                    }
//                }
//            }
//
//            @Override
//            public void afterTextChanged(Editable s) {
//
//            }
//        });

        myToast = new MyToast(this);
    }


    @Override
    protected void initListener() {

    }

    @Override
    protected void initData() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_title_back:
                finish();
                break;
            case R.id.tv_userinfo_address:
//                Intent iAddress = new Intent(mContext, UserAddressActivity.class);
//                startActivityForResult(iAddress, 1);
                closeInputMethodManager();
                areaSelectPop.show(ll_title);
                break;
            case R.id.bt_userinfo_finish:
                height = et_height.getText().toString();
                if (!TextUtils.isEmpty(height)) {
                    if (!(Double.parseDouble(height) > 0 && Double.parseDouble(height) < 300)) {
                        toastMsg(getResources().getString(R.string.userinfo_text_inputrightheight));
                        return;
                    }
                } else {
                    height = "0";
                }
                weight = et_weight.getText().toString();
                if (!TextUtils.isEmpty(weight)) {
                    if (!(Double.parseDouble(weight) > 0 && Double.parseDouble(weight) < 300)) {
                        toastMsg(getResources().getString(R.string.userinfo_text_inputrightweight));
                        return;
                    }
                } else {
                    weight = "0";
                }
                String address = tv_address.getText().toString();
                if (sex.equals(this.getResources().getString(R.string.male))) {
                    sex = "0";
                } else {
                    sex = "1";
                }
                loading();
                YiJiaHuNetWorkUtils.registerPatient(tel, password, name, age, sex, height, weight, address, areaId, et_number.getText().toString().trim(), handler);
                break;

        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 1) {
            if (data.getExtras() != null) {
                province = data.getStringExtra("province");
                city = data.getStringExtra("city");
                area = data.getStringExtra("area");
                areaId = data.getStringExtra("areaId");
                tv_address.setTextColor(ContextCompat.getColor(mContext, R.color.black_text));
                tv_address.setText(province + city + area);

                addressInput = true;
                if (weightInput && heightInput) {
                    bt_finish.setBackgroundResource(R.drawable.bg_btn_lightgreen_corner);
                    bt_finish.setEnabled(true);
                }
            }
        }
    }

    @Override
    public void onSelect(String p, String c, String a, String id) {
        province = p;
        city = c;
        area = a;
        areaId = id;
        tv_address.setTextColor(ContextCompat.getColor(mContext, R.color.black_text));
        tv_address.setText(province + city + area);


        addressInput = true;
        if (numberInput) {
            bt_finish.setBackgroundResource(R.drawable.bg_btn_lightgreen_corner);
            bt_finish.setEnabled(true);
        }
    }
}
